/*
 * @lc app=leetcode.cn id=19 lang=javascript
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
// 滑动窗口
var removeNthFromEnd = function(head, n) {
  if (!head) return null
  if (!head.next) return null
  let left = head
  let right = head
  while (n) {
    right = right.next
    n--
  }
  if (!right) {
    head = head.next
    return head
  }
  while (right.next) {
    left = left.next
    right = right.next
  }
  left.next = left.next.next
  return head
};
// @lc code=end

